package housekeeping.controller;

import housekeeping.util.AliOssUtil;
import housekeeping.util.ServerResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

import static housekeeping.util.ServerResult.error;

/**
 * ClassName: CommonController
 * Description:
 *
 * @Author 迷藏
 * @Create 2025/7/8 12:06
 * @Version 1.0
 */
@RestController
@Slf4j
@Tag(name = "通用接口")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/common/upload")
    @Operation(summary = "文件上传")
    public ServerResult<?> upload(MultipartFile file){
        log.info("文件上传：{}",file);

        try{
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //获取文件扩展名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID() +extension;
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return ServerResult.ok(filePath);
        }catch (IOException e){
            log.error("文件上传失败：{}", e);
        }

        return ServerResult.error("文件上传失败");
    }
}